package com.newbee.activity.tab;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hhu.newbee.R;
import com.newbee.activity.LoginActivity;
import com.newbee.activity.RequestFriendsListActivity;
import com.newbee.adapter.NewMsgListAdapter;
import com.newbee.app.OnRefrushActivity;
import com.newbee.app.SpeechApp;
import com.newbee.fragement.multchat.MultChatFragement;
import com.newbee.listbean.NewMsgBean;
import com.newbee.multchat.MultChatActivity;
import com.newbee.service.MainService;
import com.newbee.service.MainServiceKey;
import com.newbee.service.MainServiceTask;
import com.newbee.service.TaskType;
import com.newbee.smack.SmackClient;
import com.newbee.sqlite.DBHelper;

public class NewMsgActivity extends Activity implements OnRefrushActivity,
		OnItemClickListener, OnClickListener
{

	private TextView mEmptyView;

	private ListView mListView;
	private DBHelper mDbHelper;

	private NewMsgListAdapter mListAdapter;

	// friends
	private AlertDialog.Builder friendsbuilder;

	private int mPos;
	private List<NewMsgBean> list;
	// multchat
	private AlertDialog.Builder multchatBuilder;
	private String roomName;
	private int selectID;

	private long mExitTime;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		this.setContentView(R.layout.acitivity_newmsg);
		SpeechApp.add(this);
		mEmptyView = (TextView) this.findViewById(R.id.msglist_empty);
		mEmptyView.setOnClickListener(this);
		mListView = (ListView) this.findViewById(R.id.msglist);
		mDbHelper = new DBHelper(this);
		mListView.setOnItemClickListener(this);
		MainService.speticalAcitivity.put(this.getClass().getName(), this);
		// initListview();
		initAlertDialog();

		initLayout();

	}

	private void initAlertDialog()
	{
		multchatBuilder = new Builder(this);
		multchatBuilder.setTitle("协同录音请求");
		multchatBuilder.setMessage("是否接受协同录音请求？");

	}

	private void initLayout()
	{
		friendsbuilder = new AlertDialog.Builder(this);
		friendsbuilder.setTitle("好友添加请求");
		friendsbuilder.setMessage("是否接受添加好友邀请？");

	}

	@Override
	protected void onResume()
	{

		SharedPreferences sp = this.getSharedPreferences(
				MainActivity.SP_USR_LOGIN_STATUS, Activity.MODE_MULTI_PROCESS);

		boolean isUserLog = sp.getBoolean(MainActivity.LOGIN_STATUE, false);

		if (isUserLog)
		{
			initListview();
		}
		else
		{
			mEmptyView.setText("您未登录，请点击登录！");
			mListView.setEmptyView(mEmptyView);
		}
		super.onResume();
	}

	private void initListview()
	{

		list = mDbHelper.selectMsg();

		if (list.size() == 0)
		{
			mEmptyView.setText("您的消息列表为空");
			mListView.setEmptyView(mEmptyView);
		}
		else
		{
			if (mListAdapter == null)
			{

				mListAdapter = new NewMsgListAdapter(this, list);
				mListView.setAdapter(mListAdapter);
			}
			else
			{
				mListAdapter.setList(list);
				mListAdapter.notifyDataSetChanged();
			}
		}

	}

	@Override
	public void init()
	{
		// TODO Auto-generated method stub

	}

	@Override
	public RtInfo refresh(int taskID, Object... paras)
	{

		switch (taskID)
		{

		case TaskType.ASK_FOR_FRIEND:
		case TaskType.INVITE_MULT_CHAT:
		{
			SharedPreferences sp = this.getSharedPreferences(
					MainActivity.SP_USR_LOGIN_STATUS,
					Activity.MODE_MULTI_PROCESS);

			boolean isUserLog = sp.getBoolean(MainActivity.LOGIN_STATUE, false);
			if (isUserLog)
			{
				initListview();
			}
			break;
		}
		case TaskType.ASCEPT_FRIEND:
		{
			boolean b = (Boolean) paras[0];
			if (b)
			{
				mDbHelper.upDateFriendsAsk(mPos);//
				Toast.makeText(this, "成功接受好友", Toast.LENGTH_LONG).show();
				initListview();
			}
			else
			{
				Toast.makeText(this, "接受加友申请出现问题！", Toast.LENGTH_LONG).show();
			}
			break;
		}
		case TaskType.ACCEPT_MULT:
		{
			mDbHelper.upDateFriendsAsk(selectID);
			// mDbHelper.solveInviteMultChat(selectID);
			Intent intent = new Intent(this, MultChatActivity.class);

			String[] array = roomName.split("@")[0].split("\\$");
			String pureName = array[array.length - 1];
			intent.putExtra(MultChatFragement.CHAT_ROOM_MAME, pureName);// 纯md5
			intent.putExtra(MultChatFragement.INIT_STATE, 2);
			intent.putExtra(MultChatFragement.MASTER_TAG, false);
			this.startActivity(intent);
			break;
		}
		default:
			break;
		}

		return null;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int p, long arg3)
	{
		NewMsgBean bean = list.get(p);
		if (bean.getMsgtype() == NewMsgBean.MsgType.FRIRND)
		{

			dealWithFriend(bean, v, p);
		}
		else
		{
			dealWithMultChat(bean, v, p);
		}

	}

	private void dealWithFriend(final NewMsgBean bean, View v, int p)
	{
		TextView statusTextView = (TextView) v.findViewById(R.id.msg_status);
		String statueStr = statusTextView.getText().toString();
		if (statueStr != null && statueStr.equals("[未处理]"))
		{

			// final FriendsAskBean bean = list.get(p);

			mPos = bean.getId();
			friendsbuilder.setPositiveButton("接受",
					new DialogInterface.OnClickListener()
					{

						@Override
						public void onClick(DialogInterface arg0, int arg1)
						{

							Map<String, Object> map = new HashMap<String, Object>();
							map.put(MainServiceKey.ASK_FOR_FRIEND_POCKET_FROM,
									bean.getFromFriend());
							map.put(MainServiceKey.ASK_FOR_FRIEND_POCKET_TO,
									bean.getToFriend());

							MainServiceTask mst = new MainServiceTask(
									TaskType.ASCEPT_FRIEND, map, this
											.getClass().getName());
							MainService.addActivityMap(this.getClass()
									.getName(), NewMsgActivity.this);
							MainService.addTaskQueue(mst);

						}
					});
			friendsbuilder.setNegativeButton("拒绝",
					new DialogInterface.OnClickListener()
					{
						@Override
						public void onClick(DialogInterface arg0, int arg1)
						{

							SmackClient.getInstance().refushAskFriend(
									bean.getFromFriend(), bean.getToFriend());
							Toast.makeText(NewMsgActivity.this, "已拒绝加为好友",
									Toast.LENGTH_LONG).show();
							// RequestFriendsListActivity.this.finish();
							mDbHelper.upDateFriendsAsk(bean.getId());
						}
					});
			friendsbuilder.show();
		}

	}

	private void dealWithMultChat(final NewMsgBean bean, View v, int p)
	{
		TextView status = (TextView) v.findViewById(R.id.msg_status);

		roomName = bean.getRoom();
		selectID = bean.getId();
		if (status.getText().toString().equals("[未处理]"))
		{
			multchatBuilder.setPositiveButton("接受",
					new DialogInterface.OnClickListener()
					{

						@Override
						public void onClick(DialogInterface arg0, int arg1)
						{

							SmackClient sc = SmackClient.getInstance();

							Map<String, Object> paras = new HashMap<String, Object>();
							paras.put(MainServiceKey.MULT_CHAT_ROOM_NAME,
									roomName.split("@")[0]);

							MainServiceTask msk = new MainServiceTask(
									TaskType.ACCEPT_MULT, paras, this
											.getClass().getName());

							MainService.addActivityMap(this.getClass()
									.getName(), NewMsgActivity.this);
							MainService.addTaskQueue(msk);

						}
					});

			multchatBuilder.setNegativeButton("拒绝",
					new DialogInterface.OnClickListener()
					{

						@Override
						public void onClick(DialogInterface arg0, int arg1)
						{

							// mDbHelper.solveInviteMultChat(selectID);
							mDbHelper.upDateFriendsAsk(bean.getId());
							initListview();
						}
					});
			multchatBuilder.create().show();
		}

	}

	public boolean onKeyDown(int keyCode, KeyEvent event)
	{

		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			if ((System.currentTimeMillis() - mExitTime) > 2000)
			{
				Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
				mExitTime = System.currentTimeMillis();

				return true;
			}
			else
			{
				SpeechApp.exit();
				return true;
			}

		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.msglist_empty:
		{
			SharedPreferences sp = this.getSharedPreferences(
					MainActivity.SP_USR_LOGIN_STATUS,
					Activity.MODE_MULTI_PROCESS);

			boolean isUserLog = sp.getBoolean(MainActivity.LOGIN_STATUE, false);
			if (isUserLog)
			{
				// do nothing
			}
			else
			{
				Intent intent = new Intent(this, LoginActivity.class);
				startActivity(intent);
			}

			break;
		}

		default:
			break;
		}
	}
}
